package service

import (
	"context"
	"errors"
	"golang.org/x/crypto/bcrypt"
	"webook/internal/domain"
	"webook/internal/repostiory"
)

var (
	ErrUserDuplicateEmail    = repostiory.ErrUserDuplicateEmail
	ErrInvalidUserOrPassword = errors.New("邮箱或密码不正确")
)

type UserService struct {
	repo *repostiory.UserRepostiory
}

func NewUserService(repo *repostiory.UserRepostiory) *UserService {
	return &UserService{repo: repo}
}

func (srv *UserService) SignUp(ctx context.Context, u domain.User) error {
	hash, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	u.Password = string(hash)
	return srv.repo.Create(ctx, u)
}

func (srv *UserService) Login(ctx context.Context, email, password string) (domain.User, error) {
	u, err := srv.repo.FindByEmail(ctx, email)
	if err == repostiory.ErrUserNotFind {
		return u, ErrInvalidUserOrPassword
	}
	if err != nil {
		return u, err
	}

	err = bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
	if err != nil {
		//密码错误
		return u, err
	}
	return u, err
}
